const jwt = require("jsonwebtoken");
const userModel = require("../db/model/userModel");
const UserModel = require("../db/model/userModel")
// 中间件 拦截器 就是个函数
async function auth (req,res,next) {
  console.log("拦截器",req.headers)
  const { authorization = "" } = req.headers||{};
  const token = authorization.split("Bearer ")[1]
  console.log("1111",token)
  // token缺失
  if(!token) return  res.send({ code: -999,msg: 'token缺失'})
  // 验证token是否合法
  let userInfo = {}
  try {
    userInfo = jwt.verify(token,"2216")
  } catch (error) {
    console.log(error)
    return res.send({ code: -998,msg: 'token非法'})
  }
  // 判断tokon 有效 拿用户的id 和 token 查数据库
  const count = await userModel.find({_id: userInfo._id,token}).count();
  if(!count) return res.send({ code: -997,msg: 'token失效'})
  next();
}

module.exports = auth;